package com.demo.ai.springaidemo.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class HttpClientUtil {


    /**
     * 使用 RestTemplate 进行同步 HTTP 请求
     */
    public static String sendSyncRequest(String url, HttpMethod method, Map<String, String> headers, String body) {
        // 创建 HttpHeaders 对象
        HttpHeaders httpHeaders = new HttpHeaders();
        headers.forEach(httpHeaders::set);

        // 根据 method 是否有请求体，创建合适的 HttpEntity
        HttpEntity<String> entity = new HttpEntity<>(body, httpHeaders);

        RestTemplate restTemplate = new RestTemplate();

        // 使用 RestTemplate 发送请求，并获取响应
        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);

        // 返回响应体内容
        return response.getBody();
    }

}
